package com.easyse.serviceuser.service.impl;


import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;

import com.easyse.model.DO.LoginUser;
import com.easyse.model.DO.User;
import com.easyse.serviceuser.mapper.*;

import com.easyse.serviceuser.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;

import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.stereotype.Service;

import java.util.List;
/*
实现用户信息验证类 到数据库中校验用户信息
 */

@Service
public class UserDetailsServiceImpl implements UserDetailsService {
    @Autowired
    private UserMapper userMapper;

    @Autowired
    private UserService userService;

    @Override
    public UserDetails loadUserByUsername(String username)   {
        // 查询用户信息
        LambdaQueryWrapper<User> queryWrapper = new LambdaQueryWrapper<>();
        User user = null;
        queryWrapper.eq(User::getUsername,username);
        try {
             user = userMapper.selectOne(queryWrapper);
        } catch (Exception e ){
            e.printStackTrace();
        }

        //如果没查到这个用户
        if(user == null){
            throw new NullPointerException("用户不存在!");
        }
        //查到了这个用户 查询它的权限信息

        List<String> perms = userService.selectPermsByUserId(user.getId());

//        System.out.println("::::::::::::::::\n"+perms+"\n:::::::::::\n");
        //把数据封装成UserDetails返回
        return new LoginUser(user, perms);
    }
}
